package io.gitee.kotle.android.utils

import java.lang.StringBuilder

/**
 * list转为string
 */
fun <T> List<T>?.toStr(
    split: String = ",",
    transform: Function1<T, String> = { it.toString() }
): String {
    this ?: return ""
    val sb = StringBuilder()
    val count = this.count()
    this.forEachIndexed { index, t ->
        sb.append(transform.invoke(t))
        if (index + 1 != count) {
            sb.append(split)
        }
    }
    return sb.toString()
}

/**
 * 数组转str
 */
fun <T> Array<T>?.toStr(
    split: String = ",",
    transform: Function1<T, String> = { it.toString() }
): String {
    this ?: return ""
    val sb = StringBuilder()
    val count = this.count()
    this.forEachIndexed { index, t ->
        sb.append(transform.invoke(t))
        if (index + 1 != count) {
            sb.append(split)
        }
    }
    return sb.toString()
}

/**
 * 判断字符串是否是null
 */
fun String?.ifNull(): String? {
    return if (this.isNullOrBlank()) {
        null
    } else {
        this
    }
}


/**
 * 处理首字母
 */
inline fun String.firstCharEach(
    split: Char = ' '/*分割标志*/,
    firstEnable: Boolean = true/*首字母是否处理*/,
    block: (Char) -> String?
): String {
    val sb = StringBuilder()
    var callNextLetter = firstEnable
    this.forEach { c ->
        if (callNextLetter) {
            if (c == split) {
                sb.append(c)
            } else {
                callNextLetter = false
                block.invoke(c)?.let {
                    sb.append(it)
                }
            }
        } else {
            sb.append(c)
            //下个字符需要处理
            if (c == split) {
                callNextLetter = true
            }
        }
    }
    return sb.toString()
}

/**
 * 首字母大写
 */
fun String.firstCharUppercase(
    split: Char = ' '/*分割标志*/,
    firstEnable: Boolean = true/*首字母是否处理*/
): String {
    return firstCharEach(split, firstEnable) {
        it.uppercase()
    }
}